import { getData } from '~/server/plugins/getData'

export default defineEventHandler(async (event) => {
  try {
    // 获取查询参数
    const query = getQuery(event)
    const dataSource = query.dataSource as string // 可选参数，指定数据源
    
    // 使用插件提供的数据
    const { getCurrentRequestData, getDataSourceData } = getData()
    
    let categoryData: any = null
    
    if (dataSource) {
      // 如果指定了数据源，使用指定的数据源
      categoryData = getDataSourceData(dataSource)
    } else {
      // 否则使用当前域名的数据
      const currentData = getCurrentRequestData(event)
      if (currentData) {
        categoryData = currentData.data
      }
    }
    
    if (!categoryData) {
      return {
        success: false,
        message: '无法获取分类数据',
        data: [],
        total: 0
      }
    }
    
    // 构建一级分类列表，包含统计信息
    const mainCategories = categoryData.mainCategories.map((category: string) => {
      const subCategoryCount = categoryData.subCategories[category]?.length || 0
      const appCount = Object.values(categoryData.categoryData[category] || {}).reduce((total: number, apps: any) => {
        return total + (Array.isArray(apps) ? apps.length : 0)
      }, 0)
      
      return {
        name: category,
        displayName: category, // 前
        subCategoryCount,
        appCount,
        description: `包含 ${subCategoryCount} 个二级分类，总计 ${appCount} 个应用`
      }
    })
    
    return {
      success: true,
      message: '获取一级分类列表成功',
      data: mainCategories,
      total: mainCategories.length,
      dataSource: dataSource || 'current'
    }
    
  } catch (error: any) {
    console.error('获取一级分类列表错误:', error)
    return {
      success: false,
      message: '获取一级分类列表过程中发生错误',
      data: [],
      total: 0,
      error: process.env.NODE_ENV === 'development' ? error?.message : undefined
    }
  }
}) 